import _ from 'lodash';
import lodash from 'lodash';
import { connect } from 'umi';
import { Button, Row, Col, message } from 'antd';
import { Ref, useState, useRef, useEffect, useMemo } from 'react';

import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { onCloseModalCommon } from '@/utils';

import '../style.less';
import { MaterialService } from './/MaterialService';
import { UpdateNeedMaterialModalRight } from './UpdateNeedMaterialModalRight';
import { UpdateNeedMaterialModalLeft } from './UpdateNeedMaterialModalLeft';
import { getMaterialTableColumns } from './SelectMaterialColumns';

/**
 * @UpdateNeedMaterialModal 物料选择弹窗组件
 * @param onClose 关闭物料弹窗
 * @param onSave 保存选中物料数据
 * @returns
 */
// React.FC<NeedUpdateAPI.IUpdateNeedMaterialModal>
const UpdateNeedMaterialModal = ({ curRes, onClose, onSave, materialList }: Record<string, any>) => {
  /** 样式 */
  const prefixCls = 'apply-need-update-';

  /** 弹框ref */
  const reloadLayoutRef: Ref<IOneModalRef> = useRef(null);

  /** 表格选中内容 */
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  /** 表格选中record */
  const [selectRows, setSelectRows] = useState<Record<string, any>[]>([]);

  /** 选中树的key */
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);

  /** 左侧类型树搜索 */
  const [typeTreeSearchObj, setTypeTreeSearchObj] = useState<Record<string, any>>({
    searchValue: '',
    expandedKeys: [],
    // autoExpandParent: false,
  });

  /** 右侧表格数据展示字段 */
  const [tableList, setTableList] = useState<Record<string, any>[]>([]);

  /** 获取物料列表 */
  const { getMaterialRun, getMaterialLoading, getMaterialDataSource, getMaterialTableProps, manageTableParams } = MaterialService().getMaterialService({
    curRes,
  });

  /**回显物料数据*/
  useEffect(() => {
    if (materialList && materialList?.length) {
      /** 详情数据返回的物料信息，保存key值反显，保存row存储数据 */
      let Keys: any[] = [];
      let Rows: any[] = [];
      materialList?.forEach((item) => {
        Keys?.push(item?.materialID);
        Rows?.push({ ...item, materialIDS: item?.materialID });
      });
      /** 保存id和数据，反选中时候要用到 */
      setSelectedRowKeys(Keys);
      setSelectRows(Rows);
    }
  }, [materialList]);

  useEffect(() => {
    /** dateGrid 将物料id赋值给新字段【materialIDS】*/
    const newMaterialList = getMaterialDataSource?.map((item: Record<string, any>) => {
      /** 在物料表中，物料id是id */
      return {
        ...item,
        materialIDS: item?.id,
        materialID: item?.id,
        materialName: item?.fullName,
        needMID: item?.id, //【需求物料id（needMID ）：在月度计划是需求物料id,在零星采购时是物料id,共用一个字段】
        // supplyType: null,
        // supplyTypeName: null,
      };
    });

    /** 克隆一份数据 */
    const tempData = lodash.cloneDeep(newMaterialList);
    /** 需求详情物料数据修改后数据同步到弹窗接口获取的数据 */
    selectRows?.forEach((target) => {
      tempData.map((item: Record<string, any>, index: number) => {
        if (item.materialIDS == target.materialIDS) {
          //【预估单价（元）】
          tempData[index]['expectPrice'] = target?.expectPrice;
          //【需求数量】
          tempData[index]['expectNum'] = target?.expectNum;
          //【标的类型】
          // tempData[index]['supplyType'] = target?.supplyType;
          // tempData[index]['supplyTypeName'] = target?.supplyTypeName;
        }
      });
    });
    setTableList(tempData || []);
  }, [getMaterialDataSource]);

  /**保存选中物料 */
  const changeSure = () => {
    if (!selectRows?.length) {
      message?.warn('请选择要进行申请的物料！');
      return;
    }

    const newRows = selectRows?.map((item) => {
      let newObj = { ...item };
      if (!('importFlag' in item)) {
        newObj.importFlag = 0;
      }
      if (!('singleFlag' in item)) {
        newObj.singleFlag = 0;
      }
      return newObj;
    });

    // 筛选出空值【采购单价】【采购数量】【标的类别】
    const resObj = newRows?.find((item) => {
      if (!item?.expectPrice || !item?.expectNum || !item?.supplyType) {
        return item;
      }
    });

    if (resObj) {
      message?.warn('选中物料信息是否填充有误！');
    } else {
      newRows?.forEach((item) => (item.expectSum = Number(item?.expectNum || 0) * Number(item?.expectPrice || 0)));
      onSave(newRows);
      onCloseModalCommon(reloadLayoutRef);
    }
  };

  /**处理表格的多次选中*/
  const rowSelection = useMemo(() => {
    return {
      selectedRowKeys,
      onSelect: (record: any, selected: any) => {
        if (selected) {
          /** 添加 */
          setSelectedRowKeys([...selectedRowKeys, record?.materialIDS]); // 保存key
          setSelectRows([...selectRows, record]); // 保存record
        } else {
          /** 去除 */
          const rowsList = selectRows?.filter((item) => record?.materialIDS != item?.materialIDS);
          setSelectedRowKeys(rowsList?.map((i: Record<string, any>) => i?.materialIDS));
          setSelectRows(rowsList);
        }
      },
      onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
        let dataKeys: any[] = []; // 当前table渲染的数据key集合
        tableList?.forEach((item: Record<string, any>) => {
          dataKeys?.push(item?.materialIDS);
        });
        if (selected) {
          //全选
          // 两个key合并去重
          let keylist = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
          setSelectedRowKeys(keylist);
          // 处理record
          setSelectRows([...selectRows, ...changeRows]);
        } else {
          //全不选
          // 处理key
          let newarr: any[] = selectedRowKeys?.filter((item) => {
            return !dataKeys?.includes(item);
          });
          setSelectedRowKeys(newarr);
          /**
           * 处理row 这里的changeRows代表被取消的rows集合
           * {keys} 拿的是被取消的rows集合的id集合
           * 再已经选择的数据中进行过滤
           * */
          let keys: any[] = [];
          changeRows?.forEach((item: any) => {
            keys?.push(item?.materialIDS);
          });
          const newRows = selectRows?.filter((item) => {
            return keys?.indexOf(item?.materialIDS) == -1;
          });
          setSelectRows(newRows);
        }
      },
    };
  }, [selectRows, selectedRowKeys, tableList]);

  /**左侧数据点击事件过滤数据*/
  const onSelectLeftTree = (val: string | null) => {
    if (val) {
      getMaterialRun({ ...manageTableParams, materialType: val });
    } else {
      getMaterialRun({ ...manageTableParams, materialType: null });
    }
  };

  /**表格内容输入*/
  const onEditTableFun = (key, val, record) => {
    let { materialID } = record;
    const nodeIndex = tableList?.findIndex((item) => item?.materialID === materialID);
    let cloneTableList = _?.cloneDeep(tableList);

    if (key == 'supplyType') {
      cloneTableList[nodeIndex][key] = val?.value;
      cloneTableList[nodeIndex][key + 'Name'] = val?.label;
    } else {
      cloneTableList[nodeIndex][key] = val || 1;
    }
    setTableList(cloneTableList);

    // 价格和数量同步
    const selectRowIndex = selectRows?.findIndex((item) => item?.materialID === materialID);
    if (selectRowIndex != -1) {
      let cloneSelectRows = _?.cloneDeep(selectRows);
      if (key == 'supplyType') {
        cloneSelectRows[selectRowIndex][key] = val?.value;
        cloneSelectRows[selectRowIndex][key + 'Name'] = val?.label;
      } else {
        cloneSelectRows[selectRowIndex][key] = val || 1;
      }
      setSelectRows(cloneSelectRows);
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={reloadLayoutRef}
        title={'物料列表'}
        className={prefixCls + 'oneModal'}
        width={document.body.clientWidth * 0.8}
        onCancel={() => {
          onClose(false);
        }}
        footer={
          <>
            <Button onClick={() => onCloseModalCommon(reloadLayoutRef)}>取消</Button>
            <Button type={'primary'} onClick={changeSure}>
              确认
            </Button>
          </>
        }
        bodyStyle={{
          padding: '2px 8px',
          height: document.body.clientHeight * 0.65,
          display: 'flex',
          flexDirection: 'column',
        }}
        centered
      >
        <Row gutter={[10, 16]} className={prefixCls + 'oneModal-oneModalBox'}>
          <Col span={5}>
            <UpdateNeedMaterialModalLeft
              prefixCls={prefixCls}
              onSelect={onSelectLeftTree}
              onTreeKey={{ selectKeys, setSelectKeys }}
              leftTreeSeatchObj={{ typeTreeSearchObj, setTypeTreeSearchObj }}
            />
          </Col>
          <Col span={19}>
            <UpdateNeedMaterialModalRight
              prefixCls={prefixCls}
              selectedRowKeys={selectedRowKeys}
              getMaterialRun={(res, type) => {
                if (type && type == 'reset') {
                  setSelectKeys([]);
                  setTypeTreeSearchObj({ searchValue: '', expandedKeys: [] });
                  getMaterialRun({});
                } else {
                  getMaterialRun({ ...res, materialType: selectKeys?.toString() || null });
                }
              }}
              getMaterialLoading={getMaterialLoading}
              dataSource={tableList}
              rowSelection={rowSelection}
              getMaterialTableColumns={getMaterialTableColumns(onEditTableFun)}
              getMaterialTableProps={getMaterialTableProps}
            />
          </Col>
        </Row>
      </OneModal>

      {/* 新增物料弹窗 */}
      {/* {isShowAddMateril ? <UpdateNeedMaterialAddModal prefixCls={prefixCls} onClose={() => setIsShowAddMateril(false)} /> : <></>} */}
    </>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(UpdateNeedMaterialModal);
